package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.util.JwtUtils;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
//这个注解要搭配final使用
// 它会为类中所有带有 final 修饰的字段自动生成一个构造函数（从而实现依赖注入） 不用@Autowired
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @param gender
     * @return
     */
    @Override
    public PageResult page(Integer page, Integer pageSize, String name, Integer gender) {
        Long total = userMapper.count();
        Integer start = (page-1)*pageSize;
        List<User> list =userMapper.list(start,pageSize,name,gender);
        return new PageResult(total,list);
    }

    /**
     *登录操作
     * @param user
     * @return
     */
    @Override
    public LoginInfo login(User user) {
        //将获取的数据赋值给LoginInfo实例
        User userInfo= userMapper.getJwt(user);
        //如果查到则生成令牌
        if (userInfo!=null){
            LoginInfo loginInfo = new LoginInfo();
            //将第一个参数的属性值赋值给第二个（新方法）
            BeanUtils.copyProperties(userInfo,loginInfo);
            //生成token令牌
            Map<String,Object> payload = new HashMap<>();
            payload.put("id",userInfo.getId());
            payload.put("username",userInfo.getUsername());
            payload.put("name",userInfo.getName());
            String token = JwtUtils.creatJwt(payload);
            loginInfo.setToken(token);
            return loginInfo;
        }
        //没有结果
        return null;
    }
}
